package com.ye.spring.proxy;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Aspect
@Component
@Order(value = 1)
public class DynamicProxy {



    //切入点重用,匹配类下的所有方法
    @Pointcut("execution(* com.ye.spring.proxy.CalculatorImpl.*(..))")
    public void pointCut() {}


//    @Before("execution(public int com.ye.spring.proxy.CalculatorImpl.add(..))")
    @Before("pointCut()")
    public void beforeAdd(JoinPoint joinPoint) {

        //获取参数、方法名
        Object[] args = joinPoint.getArgs();
        Signature signature = joinPoint.getSignature();
        String methodName = signature.getName();
        System.out.println("方法执行前, 方法名：" + methodName + "参数：" + Arrays.toString(args));
    }

    @AfterReturning(value = "pointCut()", returning = "result")
    public void afterAdd(Object result) {
        System.out.println("after returning 返回结果：" + result);
    }

    @After("pointCut()")
    public void after() {
        System.out.println("after");
    }

    @AfterThrowing(value = "pointCut()", throwing = "ex")
    public void afterThrow(Throwable ex) {
        System.out.println("after throwing 返回异常" + ex.getMessage());
    }

    @Around("pointCut()")
    public Object around(ProceedingJoinPoint joinPoint) {

        Object res = null;
        try {
            System.out.println("环绕通知-前置通知");
            res = joinPoint.proceed();
            System.out.println("环绕通知-返回通知");
        } catch (Throwable e) {
            System.out.println("环绕通知-异常通知");
            e.printStackTrace();
        } finally {
            System.out.println("环绕通知-后置通知");
        }
        return res;
    }
}
